import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@Component({
	selector: 'sa-complaint-record',
	templateUrl: './complaint-record.component.html',
	styleUrls:['./complaint-record.component.css'],
})
export class ComplaintRecordComponent implements OnInit {
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	tableParam:any = {
        carNumber:'',
        companyId: '',
	    companyName: '',
		complainPhenomenon: '',
		complainTime: '',
        complainPath: '',
        reasons: '',
        isNotice: '',
        conversationPath: '',
        isFix: '',
        fixTime: '',
        remark: '',
        startTime: '',
        endTime: '',
        dateType: '',
        // searchKey: ''
	}
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage||1;
		});
	}
	companySelected(data) {
        this.tableParam.companyId = data.companyId||'';
        this.tableParam.companyName = data.companyName;
    }
	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.tableParam.startTime = time.startTime;
		this.tableParam.endTime = time.endTime;
	} 
	ngOnInit() {
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.select2Car(); //初始化select 2 车辆
			});
		})
		this.load();
	}
	//table刷新
    refresh() {
    	this.load();
    }
	//表格搜索
	tableSearch() {
		this.curPage = 1;
		this.load();
	}
	//删除
    tableDel(row) {
        this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
            this.jsonApiService.http("projectOperations/delComplain.html",'id='+row.id).subscribe(data=>{
                this.jsonApiService.message(data.message);
                if(data.success){
                    this.load();
                }
            })
        })
    }
    //分页回调
    paginate(e){
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
	//初始化加载list数据
	load(){
		let timeCheck = common.correctTimeParams(this.tableParam.startTime,this.tableParam.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				deviceId: this.tableParam.deviceId,
			    dateType: this.tableParam.dateType,
				companyId: this.tableParam.companyId,
				carNumber: this.tableParam.carNumber,
				startTime: this.tableParam.startTime,
				endTime: this.tableParam.endTime,
				reasons: this.tableParam.reasons,
				// searchKey:common.stringTrim(this.tableParam.searchKey)
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("projectOperations/findComplaintList.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				

				for(var i=0;i<data.exhibitDatas.length;i++){
					if(data.exhibitDatas[i].callDuration){
						data.exhibitDatas[i].duration = common.secondToDate(data.exhibitDatas[i].callDuration)
					}
				}

				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;

			}else{
				this.jsonApiService.message(data.message);
			}
		})
    }
	// 新增
	tableAdd() {
	    this.router.navigate(['/wx-bind/complaint-record/complaint-record-page'], {queryParams: {type:'new'}});
	}
	// 编辑
	tableEdit(row) {
        this.router.navigate(['/wx-bind/complaint-record/complaint-record-page'], {queryParams: {id: row.id,type: 'updata',nowPage:this.curPage}});
	}
    //拉取车辆数据
	select2Car() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function(params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function(e) {
			var data = e.params.data;
			that.tableParam.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.tableParam.carNumber = data.text.split('[')[0];
			} else {
				that.tableParam.carNumber = data.text;
			}
		});
	}
    //select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
    }
    del_carNumber(){
		this.tableParam.deviceId = '';
		this.tableParam.carNumber = '';
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title","");
        $("#select2-carNumberSelect2-container").prepend(str);
	}
	imgList: any = [];
	imgLocalList:any=[];
	showImg1(row,modal){
		this.imgList = [];
		this.imgLocalList = [];
		
		this.imgList = row.complainPath.split(",");
		let localImg;
		for(var i=0;i< this.imgList.length;i++){
			// if(this.imgList[i][0] == '/'){
			// 	localImg = config.BaseURL + this.imgList[i].substr(1);
			// }else{
			// 	localImg = config.BaseURL + this.imgList[i][i];
			// }

			if(this.imgList[i].indexOf('http') == -1){
				if(this.imgList[i][0] == '/'){
					localImg = config.BaseURL + this.imgList[i].substr(1);
				}else{
					localImg = config.BaseURL + this.imgList[i];
				}
			}else{
				localImg = this.imgList[i];
			}

			this.imgLocalList.push(localImg);
		}
		
		modal.show();
		if(this.isViewer1 && $(".viewer-container").length >0){
			this.viewer1.destroy();
		}

	}
	showImg2(row,modal){

		this.imgList = [];
		this.imgLocalList = [];
		this.imgList = row.conversationPath.split(",");

		let localImg;
		for(var i=0;i< this.imgList.length;i++){
			// if(this.imgList[i][0] == '/'){
			// 	localImg = config.BaseURL + this.imgList[i].substr(1);
			// }else{
			// 	localImg = config.BaseURL + this.imgList[i][i];
			// }
			if(this.imgList[i].indexOf('http') == -1){
				if(this.imgList[i][0] == '/'){
					localImg = config.BaseURL + this.imgList[i].substr(1);
				}else{
					localImg = config.BaseURL + this.imgList[i];
				}
			}else{
				localImg = this.imgList[i];
			}
			this.imgLocalList.push(localImg);
		}
		modal.show();

		if(this.isViewer2 && $(".viewer-container").length >0){
			this.viewer2.destroy();
		}
	}
	closeImgModal1(modal){
		modal.hide();
		this.imgList = [];
		this.imgLocalList = [];
	}
	closeImgModal2(modal){
		modal.hide();
		this.imgList = [];
		this.imgLocalList = [];
	}
	isViewer1:boolean = false; //默认隐藏
	isViewer2:boolean = false; //默认隐藏
	//显示图片组件
	viewer1: any='';
	viewer2: any='';
	//图片放大
	bigimg(type,row){
		if(this.isViewer1 && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showBigImg(type);
					})
				})
			})
		}else{
			this.showBigImg(type);
		}

	}
	showBigImg(type){
		var that = this;
		var imgList
		if(type == 'Modal1'){
			imgList = $(".imagesInfo1")[0];
			this.viewer1 = new Viewer(imgList, {
				url: 'src',
				title: function (image) {
					return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
				},
			});
			that.isViewer1 = true

		}else{
			imgList = $(".imagesInfo2")[0];
			this.viewer2 = new Viewer(imgList, {
				url: 'src',
				title: function (image) {
					return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
				},
			});
			that.isViewer2 = true
		}
		
	}

	//导出
	export_data() {
		var parameters = {
			deviceId: this.tableParam.deviceId,
			dateType: this.tableParam.dateType,
			companyId: this.tableParam.companyId,
			carNumber: this.tableParam.carNumber,
			startTime: this.tableParam.startTime,
			endTime: this.tableParam.endTime,
			reasons: this.tableParam.reasons,
			// searchKey:common.stringTrim(this.tableParam.searchKey)
		};
		let timeCheck = common.correctTime(parameters, ['dateType'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'projectOperations/exportComplainList.html')
	}

	//是否同步
	tableTong(row){
		// modal.show();
		this.jsonApiService.confirm_message("是否确定同步维修状态").then(()=>{
            this.jsonApiService.http("projectOperations/synchronizationRepairedState.html",'id='+row.id).subscribe(data=>{
                this.jsonApiService.message(data.message);
                if(data.success){
                    this.load();
                }
            })
        })
	}
}